import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Time implements Comparable<Time>
{
	private int minutes;

	public Time(int hours, int minutes)
	{
		setTime(hours, minutes);
	}

	public Time(Time time)
	{
		setTime(0, time.getMinutes());
	}

	public void setTime(int hours, int minutes)
	{
		this.minutes = hours * 60 + minutes;
	}

	public void tick()
	{
		this.minutes++;
	}

	public int getMinutes()
	{
		return minutes;
	}

	public Time add(TimeDuration duration)
	{
		return new Time(0, minutes + duration.getMinutes());
	}
	
	/**
	 * Generates a random time after the given time, but before the end of the day.
	 * @param start
	 * @param end
	 * @return
	 */
	public static Time randomBetween(Time start, Time end){
		int interval = end.getMinutes() - start.getMinutes();
		int added = (int)(Math.random() * interval) + 1;
		
		int hour = (start.getMinutes() + added) / 60;
		if(hour == 12){
			hour++;
		}
		int minutes = (start.getMinutes() + added) % 60;
		return new Time(hour, minutes);
	}

	@Override
	public String toString()
	{
		int hours = minutes / 60;
		int minutesInHour = minutes % 60;
		Calendar calendar = new GregorianCalendar();
		calendar.set(Calendar.HOUR_OF_DAY, hours);
		calendar.set(Calendar.MINUTE, minutesInHour);
		Date date = calendar.getTime();
		SimpleDateFormat format = new SimpleDateFormat("h:mm a");
		return format.format(date);
	}

	@Override
	public boolean equals(Object o)
	{
		Time other = (Time) o;
		return other.minutes == minutes;
	}

	@Override
	public int compareTo(Time o)
	{
		return minutes - o.minutes;
	}
}
